<template>
  <div class="media-container">
    <h1 class="page-title">媒体资源生成</h1>
    
    <!-- 输入区 -->
    <div class="input-section" v-if="!isGenerating && !mediaResult">
      <div class="form-group">
        <label>资源类型</label>
        <div class="media-type-selector">
          <div 
            v-for="type in mediaTypes" 
            :key="type.value"
            :class="['type-item', { active: formData.mediaType === type.value }]"
            @click="selectMediaType(type.value)"
          >
            <div class="type-icon">{{ type.icon }}</div>
            <div class="type-name">{{ type.label }}</div>
          </div>
        </div>
      </div>
      
      <div class="form-group">
        <label>主题内容</label>
        <input 
          type="text" 
          v-model="formData.topic" 
          placeholder="请输入主题内容，如：人工智能在教育中的应用"
        >
      </div>
      
      <div class="form-group">
        <label>内容要点</label>
        <textarea 
          v-model="formData.contentPoints" 
          placeholder="请输入内容要点，每行一个要点"
          rows="4"
        ></textarea>
        <div class="hint">提示：输入多个要点将提高生成内容的针对性</div>
      </div>
      
      <div class="form-group">
        <label>目标受众</label>
        <select v-model="formData.audience">
          <option value="">请选择目标受众</option>
          <option 
            v-for="audience in audienceOptions" 
            :key="audience.value" 
            :value="audience.value"
          >
            {{ audience.label }}
          </option>
        </select>
      </div>
      
      <div class="form-group" v-if="showMediaSpecificOptions">
        <label>{{ getMediaSpecificLabel() }}</label>
        <div v-if="formData.mediaType === 'video'" class="duration-slider">
          <input 
            type="range" 
            v-model.number="formData.duration" 
            min="1" 
            max="10"
            step="1"
          >
          <div class="duration-value">{{ formData.duration }} 分钟</div>
        </div>
        
        <div v-if="formData.mediaType === 'image'" class="style-selector">
          <div 
            v-for="style in imageStyles" 
            :key="style.value"
            :class="['style-item', { active: formData.imageStyle === style.value }]"
            @click="formData.imageStyle = style.value"
          >
            {{ style.label }}
          </div>
        </div>
        
        <select v-if="formData.mediaType === 'audio'" v-model="formData.audioType">
          <option value="">请选择音频类型</option>
          <option 
            v-for="type in audioTypes" 
            :key="type.value" 
            :value="type.value"
          >
            {{ type.label }}
          </option>
        </select>
      </div>
      
      <button 
        class="generate-btn" 
        :disabled="!isFormValid" 
        @click="generateMedia"
      >
        确认输入，生成媒体资源
      </button>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-section" v-if="isGenerating">
      <div class="loading-spinner"></div>
      <p>正在生成媒体资源，请稍候...</p>
      <p class="loading-hint">{{ getLoadingHint() }}</p>
    </div>
    
    <!-- 结果预览区 -->
    <div class="result-section" v-if="mediaResult">
      <div class="result-header">
        <h2>{{ mediaResult.topic }}</h2>
        <div class="result-meta">
          <span class="media-type-badge">{{ getMediaTypeLabel() }}</span>
          <span class="time">生成时间：{{ mediaResult.createdAt }}</span>
        </div>
      </div>
      
      <div class="result-content">
        <!-- 视频预览 -->
        <div v-if="mediaResult.type === 'video'" class="video-preview">
          <div class="video-placeholder">
            <div class="placeholder-icon">▶</div>
            <div class="placeholder-text">视频预览（实际项目中显示真实视频）</div>
          </div>
          <div class="video-info">
            <div class="info-item">
              <span class="label">时长：</span>
              <span>{{ mediaResult.duration }}分钟</span>
            </div>
            <div class="info-item">
              <span class="label">格式：</span>
              <span>MP4</span>
            </div>
          </div>
        </div>
        
        <!-- 图片预览 -->
        <div v-if="mediaResult.type === 'image'" class="image-preview">
          <div class="image-placeholder">
            <div class="placeholder-icon">🖼️</div>
            <div class="placeholder-text">图片预览（实际项目中显示真实图片）</div>
          </div>
          <div class="image-info">
            <div class="info-item">
              <span class="label">风格：</span>
              <span>{{ getImageStyleLabel() }}</span>
            </div>
            <div class="info-item">
              <span class="label">格式：</span>
              <span>PNG</span>
            </div>
          </div>
        </div>
        
        <!-- 音频预览 -->
        <div v-if="mediaResult.type === 'audio'" class="audio-preview">
          <div class="audio-player">
            <div class="player-controls">
              <button class="play-btn">▶</button>
              <div class="progress-bar">
                <div class="progress" style="width: 0%"></div>
              </div>
              <div class="time-display">00:00 / {{ formatTime(mediaResult.duration) }}</div>
            </div>
          </div>
          <div class="audio-info">
            <div class="info-item">
              <span class="label">类型：</span>
              <span>{{ getAudioTypeLabel() }}</span>
            </div>
            <div class="info-item">
              <span class="label">格式：</span>
              <span>MP3</span>
            </div>
          </div>
        </div>
        
        <!-- 内容要点 -->
        <div class="content-points">
          <h3>内容要点</h3>
          <ul>
            <li v-for="(point, index) in mediaResult.contentPoints" :key="index">
              {{ point }}
            </li>
          </ul>
        </div>
        
        <!-- 使用建议 -->
        <div class="usage-suggestions">
          <h3>使用建议</h3>
          <p>{{ mediaResult.usageSuggestion }}</p>
        </div>
      </div>
      
      <div class="result-actions">
        <button class="action-btn edit" @click="editMedia">编辑</button>
        <button class="action-btn save" @click="saveMedia">保存</button>
        <button class="action-btn download" @click="downloadMedia">下载</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useResourceStore } from '../../stores/resourceStore'
import apiService from '../../api'

const router = useRouter()
const resourceStore = useResourceStore()

// 表单数据
const formData = ref({
  mediaType: 'video',
  topic: '',
  contentPoints: '',
  audience: '',
  duration: 3,        // 视频时长（分钟）
  imageStyle: 'flat',  // 图片风格
  audioType: ''       // 音频类型
})

// 媒体类型选项
const mediaTypes = [
  { label: '视频', value: 'video', icon: '🎬' },
  { label: '图片', value: 'image', icon: '🖼️' },
  { label: '音频', value: 'audio', icon: '🎵' }
]

// 目标受众选项
const audienceOptions = [
  { label: '小学生', value: 'primary' },
  { label: '中学生', value: 'middle' },
  { label: '高中生', value: 'high' },
  { label: '大学生', value: 'college' },
  { label: '成人学习者', value: 'adult' }
]

// 图片风格选项
const imageStyles = [
  { label: '扁平插画', value: 'flat' },
  { label: '照片写实', value: 'photo' },
  { label: '卡通风格', value: 'cartoon' },
  { label: '信息图表', value: 'infographic' }
]

// 音频类型选项
const audioTypes = [
  { label: '讲解配音', value: 'narration' },
  { label: '背景音乐', value: 'bgm' },
  { label: '音效素材', value: 'sfx' }
]

// 状态变量
const isGenerating = ref(false)
const mediaResult = ref(null)

// 是否显示媒体特定选项
const showMediaSpecificOptions = computed(() => {
  return formData.value.mediaType !== ''
})

// 表单验证
const isFormValid = computed(() => {
  const base = (
    formData.value.mediaType !== '' &&
    formData.value.topic.trim() !== '' &&
    formData.value.contentPoints.trim() !== '' &&
    formData.value.audience !== ''
  )
  
  if (formData.value.mediaType === 'video') {
    return base && formData.value.duration > 0
  } else if (formData.value.mediaType === 'image') {
    return base && formData.value.imageStyle !== ''
  } else if (formData.value.mediaType === 'audio') {
    return base && formData.value.audioType !== ''
  }
  
  return base
})

// 选择媒体类型
const selectMediaType = (type) => {
  formData.value.mediaType = type
  
  // 重置特定媒体类型的选项
  if (type === 'video') {
    formData.value.duration = 3
  } else if (type === 'image') {
    formData.value.imageStyle = 'flat'
  } else if (type === 'audio') {
    formData.value.audioType = ''
  }
}

// 获取媒体特定选项的标签
const getMediaSpecificLabel = () => {
  if (formData.value.mediaType === 'video') {
    return '视频时长'
  } else if (formData.value.mediaType === 'image') {
    return '图片风格'
  } else if (formData.value.mediaType === 'audio') {
    return '音频类型'
  }
  return ''
}

// 获取媒体类型标签
const getMediaTypeLabel = () => {
  const type = mediaTypes.find(t => t.value === mediaResult.value.type)
  return type ? type.label : ''
}

// 获取图片风格标签
const getImageStyleLabel = () => {
  if (!mediaResult.value || mediaResult.value.type !== 'image') return ''
  const style = imageStyles.find(s => s.value === mediaResult.value.imageStyle)
  return style ? style.label : ''
}

// 获取音频类型标签
const getAudioTypeLabel = () => {
  if (!mediaResult.value || mediaResult.value.type !== 'audio') return ''
  const type = audioTypes.find(t => t.value === mediaResult.value.audioType)
  return type ? type.label : ''
}

// 获取加载提示
const getLoadingHint = () => {
  if (formData.value.mediaType === 'video') {
    return '视频生成可能需要较长时间，请耐心等待'
  } else if (formData.value.mediaType === 'image') {
    return '正在根据您的要求生成图片'
  } else if (formData.value.mediaType === 'audio') {
    return '音频合成中，请稍候'
  }
  return '资源生成中...'
}

// 格式化时间
const formatTime = (minutes) => {
  const mins = Math.floor(minutes)
  const secs = Math.round((minutes - mins) * 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 生成媒体资源
const generateMedia = async () => {
  try {
    isGenerating.value = true
    
    // 准备请求参数
    const params = {
      type: formData.value.mediaType,
      topic: formData.value.topic,
      contentPoints: formData.value.contentPoints.split('\n').filter(p => p.trim() !== ''),
      audience: formData.value.audience
    }
    
    // 添加特定媒体类型的参数
    if (params.type === 'video') {
      params.duration = formData.value.duration
    } else if (params.type === 'image') {
      params.imageStyle = formData.value.imageStyle
    } else if (params.type === 'audio') {
      params.audioType = formData.value.audioType
    }
    
    // 调用API生成媒体资源
    // 实际项目中应该调用后端API
    // const response = await apiService.media.generate(params)
    
    // 模拟API响应
    await new Promise(resolve => setTimeout(resolve, 2500))
    
    // 模拟返回数据
    const mockResponse = {
      type: params.type,
      topic: params.topic,
      contentPoints: params.contentPoints,
      audience: params.audience,
      createdAt: new Date().toLocaleString()
    }
    
    // 添加特定媒体类型的返回数据
    if (params.type === 'video') {
      mockResponse.duration = params.duration
      mockResponse.url = 'https://example.com/video.mp4'
      mockResponse.usageSuggestion = '该视频适合作为课程导入或知识点讲解，建议在课堂教学中播放并组织学生讨论。'
    } else if (params.type === 'image') {
      mockResponse.imageStyle = params.imageStyle
      mockResponse.url = 'https://example.com/image.png'
      mockResponse.usageSuggestion = '该图片可用于课件制作、教材插图或课堂展示，建议配合文字说明使用以增强教学效果。'
    } else if (params.type === 'audio') {
      mockResponse.audioType = params.audioType
      mockResponse.duration = params.audioType === 'narration' ? 2.5 : 1.5
      mockResponse.url = 'https://example.com/audio.mp3'
      mockResponse.usageSuggestion = '该音频可用于多媒体课件、自主学习材料或课堂氛围营造，建议根据教学节奏适时播放。'
    }
    
    // 设置结果
    mediaResult.value = mockResponse
    
    // 保存到状态管理
    resourceStore.setMediaData(mockResponse)
    
  } catch (error) {
    console.error('生成媒体资源失败:', error)
    // 可以在这里添加错误提示
  } finally {
    isGenerating.value = false
  }
}

// 编辑媒体
const editMedia = () => {
  // 将当前结果数据填充到表单中
  formData.value.mediaType = mediaResult.value.type
  formData.value.topic = mediaResult.value.topic
  formData.value.contentPoints = mediaResult.value.contentPoints.join('\n')
  formData.value.audience = mediaResult.value.audience
  
  // 填充特定媒体类型的数据
  if (mediaResult.value.type === 'video') {
    formData.value.duration = mediaResult.value.duration
  } else if (mediaResult.value.type === 'image') {
    formData.value.imageStyle = mediaResult.value.imageStyle
  } else if (mediaResult.value.type === 'audio') {
    formData.value.audioType = mediaResult.value.audioType
  }
  
  // 清空结果，返回编辑状态
  mediaResult.value = null
}

// 保存媒体
const saveMedia = async () => {
  try {
    // 调用API保存媒体
    // 实际项目中应该调用后端API
    // await apiService.resource.save({
    //   type: 'media',
    //   data: mediaResult.value
    // })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 显示成功提示
    alert('媒体资源已保存到资源库')
    
  } catch (error) {
    console.error('保存媒体资源失败:', error)
    // 可以在这里添加错误提示
  }
}

// 下载媒体
const downloadMedia = async () => {
  try {
    // 调用API下载媒体
    // 实际项目中应该调用后端API
    // const response = await apiService.media.download(mediaResult.value.id)
    // 
    // // 创建下载链接
    // const url = window.URL.createObjectURL(new Blob([response]))
    // const link = document.createElement('a')
    // link.href = url
    // link.setAttribute('download', `${mediaResult.value.topic}.${getFileExtension()}`)
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
    
    // 模拟下载功能
    alert('下载功能在实际项目中需要后端支持')
    
  } catch (error) {
    console.error('下载媒体资源失败:', error)
    // 可以在这里添加错误提示
  }
}

// 获取文件扩展名
const getFileExtension = () => {
  if (!mediaResult.value) return ''
  
  if (mediaResult.value.type === 'video') {
    return 'mp4'
  } else if (mediaResult.value.type === 'image') {
    return 'png'
  } else if (mediaResult.value.type === 'audio') {
    return 'mp3'
  }
  
  return ''
}

// 页面加载时检查是否有已生成的媒体数据
onMounted(() => {
  const savedMedia = resourceStore.getMediaData
  if (savedMedia && savedMedia.topic) {
    mediaResult.value = savedMedia
  }
})
</script>

<style scoped>
.media-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-title {
  font-size: 1.8rem;
  margin-bottom: 24px;
  color: #333;
  font-weight: 600;
}

/* 输入区样式 */
.input-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.hint {
  font-size: 0.85rem;
  color: #888;
  margin-top: 6px;
}

input[type="text"],
textarea,
select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

input[type="text"]:focus,
textarea:focus,
select:focus {
  border-color: #4b6cb7;
  outline: none;
}

/* 媒体类型选择器样式 */
.media-type-selector {
  display: flex;
  gap: 16px;
  margin-bottom: 10px;
}

.type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.2s;
}

.type-item.active {
  background-color: #4b6cb7;
  color: white;
}

.type-icon {
  font-size: 1.8rem;
  margin-bottom: 8px;
}

.type-name {
  font-weight: 500;
}

/* 图片风格选择器样式 */
.style-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.style-item {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f5f5f5;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.9rem;
}

.style-item.active {
  background-color: #4b6cb7;
  color: white;
}

/* 时长滑块样式 */
.duration-slider {
  display: flex;
  align-items: center;
  gap: 16px;
}

.duration-slider input[type="range"] {
  flex: 1;
  height: 6px;
  -webkit-appearance: none;
  appearance: none;
  background: #ddd;
  outline: none;
  border-radius: 3px;
}

.duration-slider input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #4b6cb7;
  cursor: pointer;
}

.duration-value {
  min-width: 80px;
  text-align: right;
  font-weight: 500;
  color: #555;
}

/* 生成按钮样式 */
.generate-btn {
  width: 100%;
  padding: 12px;
  background-color: #4b6cb7;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.generate-btn:hover {
  background-color: #3b5998;
}

.generate-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 加载状态样式 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(75, 108, 183, 0.1);
  border-radius: 50%;
  border-top-color: #4b6cb7;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

.loading-hint {
  color: #888;
  font-size: 0.9rem;
  margin-top: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 结果预览区样式 */
.result-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.result-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.result-header h2 {
  margin: 0 0 8px 0;
  font-size: 1.5rem;
  color: #333;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.media-type-badge {
  background-color: #4b6cb7;
  color: white;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
}

.time {
  font-size: 0.9rem;
  color: #999;
}

/* 视频预览样式 */
.video-preview {
  margin-bottom: 24px;
}

.video-placeholder {
  background-color: #f5f5f5;
  border-radius: 8px;
  height: 240px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.placeholder-icon {
  font-size: 2.5rem;
  color: #4b6cb7;
  margin-bottom: 12px;
}

.placeholder-text {
  color: #888;
  font-size: 0.95rem;
}

.video-info,
.image-info,
.audio-info {
  display: flex;
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.info-item .label {
  font-weight: 500;
  color: #555;
}

/* 图片预览样式 */
.image-preview {
  margin-bottom: 24px;
}

.image-placeholder {
  background-color: #f5f5f5;
  border-radius: 8px;
  height: 240px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

/* 音频预览样式 */
.audio-preview {
  margin-bottom: 24px;
}

.audio-player {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.player-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.play-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #4b6cb7;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background-color: #ddd;
  border-radius: 3px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #4b6cb7;
  width: 0%;
}

.time-display {
  font-size: 0.9rem;
  color: #666;
  min-width: 90px;
  text-align: right;
}

/* 内容要点样式 */
.content-points {
  margin-bottom: 24px;
}

.content-points h3,
.usage-suggestions h3 {
  font-size: 1.2rem;
  margin: 0 0 16px 0;
  color: #333;
  font-weight: 600;
}

.content-points ul {
  margin: 0;
  padding-left: 20px;
}

.content-points li {
  margin-bottom: 8px;
  color: #555;
  line-height: 1.5;
}

/* 使用建议样式 */
.usage-suggestions {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.usage-suggestions p {
  margin: 0;
  color: #555;
  line-height: 1.6;
}

/* 结果操作按钮样式 */
.result-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.action-btn.edit {
  background-color: #f5f5f5;
  color: #666;
}

.action-btn.edit:hover {
  background-color: #e0e0e0;
}

.action-btn.save {
  background-color: #4b6cb7;
  color: white;
}

.action-btn.save:hover {
  background-color: #3b5998;
}

.action-btn.download {
  background-color: #f0f5ff;
  color: #4b6cb7;
  border: 1px solid #4b6cb7;
}

.action-btn.download:hover {
  background-color: #e6f0ff;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .media-type-selector {
    flex-direction: column;
    gap: 10px;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
  
  .video-info,
  .image-info,
  .audio-info {
    flex-direction: column;
    gap: 8px;
  }
}
</style>